<template>
    <view class="my-orders-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <text class="nav-title">我的订单</text>
        </view>
        
        <!-- 下拉刷新区域 -->
        <scroll-view 
            class="scroll-container" 
            scroll-y="true" 
            :refresher-enabled="true"
            :refresher-threshold="45"
            :refresher-triggered="refreshing"
            @refresherrefresh="onRefresh"
            @scrolltolower="onReachBottom"
        >
            <!-- 订单列表 -->
            <view class="order-list" v-if="orderList.length > 0">
                <view class="order-item" v-for="(item, index) in orderList" :key="item.id" @click="viewOrderDetail(item.id)">
                    <view class="order-header">
                        <text class="order-title">{{ item.title }}</text>
                        <text class="order-status" :class="getStatusClass(item.status)">{{ item.status }}</text>
                    </view>
                    
                    <view class="order-content">
                        <view class="order-info">
                            <view class="info-item">
                                <text class="info-label">编程语言:</text>
                                <text class="info-value">{{ item.language }}</text>
                            </view>
                            <view class="info-item">
                                <text class="info-label">预算范围:</text>
                                <text class="info-value">¥{{ item.lessBudget }} - {{ item.highBudget }}</text>
                            </view>
                            <view class="info-item">
                                <text class="info-label">期望完成:</text>
                                <text class="info-value">{{ item.expectation }}天</text>
                            </view>
                            <view class="info-item">
                                <text class="info-label">提交时间:</text>
                                <text class="info-value">{{ formatDate(item.createdTime) }}</text>
                            </view>
                        </view>
                        
                        <!-- 订单内容预览 -->
                        <view class="order-desc">{{ item.content }}</view>
                        
                        <!-- 图片预览 -->
                        <view class="image-preview" v-if="item.imageList && item.imageList.length > 0">
                            <image 
                                v-for="(img, imgIndex) in item.imageList.slice(0, 3)" 
                                :key="imgIndex" 
                                :src="img" 
                                class="preview-image" 
                                mode="aspectFill"
                                @click.stop="previewImage(item.imageList, imgIndex)"
                            ></image>
                            <view class="more-images" v-if="item.imageList.length > 3">
                                <text>+{{ item.imageList.length - 3 }}</text>
                            </view>
                        </view>
                    </view>
                    
                    <!-- 订单操作 -->
                    <view class="order-actions">
                        <button class="action-btn" @click.stop="editOrder(item.id)" v-if="item.status === '待处理'">修改订单</button>
                        <button class="action-btn" @click.stop="cancelOrder(item.id)" v-if="item.status === '待处理'">取消订单</button>
                        <button class="action-btn" @click.stop="contactService(item.id)">联系客服</button>
                    </view>
                </view>
            </view>
            
            <!-- 空状态 -->
            <view class="empty-state" v-else-if="!loading">
                <image src="/static/empty.png" class="empty-icon"></image>
                <text class="empty-text">暂无订单数据</text>
                <button class="create-btn" @click="goToCreateOrder">创建订单</button>
            </view>
            
            <!-- 加载状态 -->
            <view class="loading-state" v-if="loading">
                <view class="loading-spinner"></view>
                <text class="loading-text">加载中...</text>
            </view>
            
            <!-- 加载更多 -->
            <view class="load-more" v-if="orderList.length > 0 && hasMore && !loading">
                <text @click="loadMore">加载更多</text>
            </view>
            <view class="load-more" v-else-if="orderList.length > 0 && !hasMore">
                <text>没有更多数据了</text>
            </view>
        </scroll-view>
        
        <!-- 自定义联系方式弹窗 -->
        <view class="custom-modal" v-if="showContactModal" @click="closeContactModal">
            <view class="modal-content" @click.stop>
                <view class="modal-title">联系客服</view>
                <view class="modal-body">
                    <view class="contact-item">
                        <text class="contact-label">微信：</text>
                        <text class="contact-value" @click="copyText('hepinganheliuyi')">hepinganheliuyi</text>
                        <view class="copy-btn" @click="copyText('hepinganheliuyi')">复制</view>
                    </view>
                    <view class="contact-item">
                        <text class="contact-label">邮箱：</text>
                        <text class="contact-value" @click="copyText('1641436566@qq.com')">1641436566@qq.com</text>
                        <view class="copy-btn" @click="copyText('1641436566@qq.com')">复制</view>
                    </view>
                </view>
                <view class="modal-footer">
                    <button class="modal-btn" @click="closeContactModal">关闭</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'

// 响应式数据
const orderList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const hasMore = ref(true)
const refreshing = ref(false)
const showContactModal = ref(false)

// 下拉刷新
const onRefresh = () => {
    refreshing.value = true
    // 重置页码
    pageNum.value = 1
    
    // 获取最新数据
    fetchOrderList()
        .finally(() => {
            setTimeout(() => {
                refreshing.value = false
            }, 1000)
        })
}

// 获取订单列表
const fetchOrderList = async (isLoadMore = false) => {
    if (loading.value && !refreshing.value) return
    
    loading.value = true
    
    try {
        const res = await request('/order/myList', {
            method: 'GET',
            data: { pageNum: pageNum.value }
        })
        
        if (res.code === 200) {
            const list = res.data || []
            
            if (isLoadMore) {
                orderList.value = [...orderList.value, ...list]
            } else {
                orderList.value = list
            }
            
            // 判断是否有更多数据
            hasMore.value = list.length >= pageSize.value
        } else {
            uni.showToast({
                title: res.msg || '获取订单列表失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取订单列表失败', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 加载更多
const loadMore = () => {
    if (loading.value || !hasMore.value) return
    
    pageNum.value++
    fetchOrderList(true)
}

// 查看订单详情
const viewOrderDetail = (id) => {
    uni.navigateTo({
        url: `/pages/orders/order-detail?id=${id}`
    })
}

// 修改订单
const editOrder = (id) => {
    uni.navigateTo({
        url: `/pages/orders/edit-order?id=${id}`
    })
}

// 取消订单
const cancelOrder = (id) => {
    uni.showModal({
        title: '确认取消',
        content: '确定要取消该订单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await request('/order/cancel', {
                        method: 'POST',
                        data: id 
                    })
                    
                    if (result.code === 200) {
                        uni.showToast({
                            title: '订单已取消',
                            icon: 'success'
                        })
                        
                        // 重新加载订单列表
                        pageNum.value = 1
                        fetchOrderList()
                    } else {
                        uni.showToast({
                            title: result.msg || '取消失败',
                            icon: 'none'
                        })
                    }
                } catch (error) {
                    console.error('取消订单失败', error)
                    uni.showToast({
                        title: '网络错误，请稍后重试',
                        icon: 'none'
                    })
                }
            }
        }
    })
}

// 联系客服
const contactService = (id) => {
    showContactModal.value = true
}

// 关闭联系方式弹窗
const closeContactModal = () => {
    showContactModal.value = false
}

// 复制文本
const copyText = (text) => {
    uni.setClipboardData({
        data: text,
        success: () => {
            uni.showToast({
                title: '已复制',
                icon: 'success'
            })
        }
    })
}

// 预览图片
const previewImage = (imageList, index) => {
    uni.previewImage({
        urls: imageList,
        current: index
    })
}

// 创建订单
const goToCreateOrder = () => {
    uni.navigateTo({
        url: '/pages/orders/orders'
    })
}

// 获取状态样式类
const getStatusClass = (status) => {
    const classMap = {
        '待处理': 'status-pending',
        '处理中': 'status-processing',
        '已完成': 'status-completed',
        '已取消': 'status-canceled'
    }
    return classMap[status] || ''
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '未知'
    const date = new Date(dateString)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 页面加载时获取订单列表
onMounted(() => {
    fetchOrderList()
})

// 页面触底事件
defineExpose({
    onReachBottom: () => {
        if (hasMore.value && !loading.value) {
            loadMore()
        }
    }
})
</script>

<style lang="scss" scoped>
.my-orders-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #18122B 0%, #120C1C 100%);
    padding-bottom: 30rpx;
    display: flex;
    flex-direction: column;
    position: relative;
}

/* 导航栏样式 */
.nav-bar {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #2D1457;
}

.nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #A259FF;
}

/* 滚动区域 */
.scroll-container {
    flex: 1;
    height: calc(100vh - 80rpx);
}

/* 订单列表 */
.order-list {
    padding: 20rpx 30rpx;
}

.order-item {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx #7B2FF244;
    border: 1px solid #2D1457;
}

/* 订单头部 */
.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    border-bottom: 1px solid rgba(45, 20, 87, 0.5);
    padding-bottom: 20rpx;
}

.order-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.order-status {
    font-size: 24rpx;
    padding: 6rpx 16rpx;
    border-radius: 30rpx;
    margin-left: 20rpx;
}

.status-pending {
    background: rgba(162, 89, 255, 0.2);
    color: #A259FF;
    border: 1px solid #A259FF;
}

.status-processing {
    background: rgba(16, 174, 255, 0.2);
    color: #10AEFF;
    border: 1px solid #10AEFF;
}

.status-completed {
    background: rgba(39, 194, 129, 0.2);
    color: #27C281;
    border: 1px solid #27C281;
}

.status-canceled {
    background: rgba(255, 75, 75, 0.2);
    color: #FF4B4B;
    border: 1px solid #FF4B4B;
}

/* 订单内容 */
.order-content {
    margin-bottom: 20rpx;
}

.order-info {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
    margin-bottom: 20rpx;
}

.info-item {
    display: flex;
    align-items: center;
}

.info-label {
    font-size: 26rpx;
    color: #B8B8D1;
    margin-right: 10rpx;
}

.info-value {
    font-size: 26rpx;
    color: #fff;
}

.order-desc {
    font-size: 26rpx;
    color: #B8B8D1;
    line-height: 1.6;
    margin-bottom: 20rpx;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 图片预览 */
.image-preview {
    display: flex;
    gap: 10rpx;
    margin-top: 20rpx;
}

.preview-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    object-fit: cover;
}

.more-images {
    width: 120rpx;
    height: 120rpx;
    background: rgba(45, 20, 87, 0.5);
    border-radius: 8rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 28rpx;
}

/* 订单操作 */
.order-actions {
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    margin-top: 20rpx;
    border-top: 1px solid rgba(45, 20, 87, 0.5);
    padding-top: 20rpx;
}

.action-btn {
    background: transparent;
    border: 1px solid #7B2FF2;
    color: #A259FF;
    font-size: 26rpx;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    line-height: 1.5;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

.empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
}

.empty-text {
    font-size: 28rpx;
    color: #B8B8D1;
    margin-bottom: 40rpx;
}

.create-btn {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    color: #fff;
    font-size: 28rpx;
    padding: 15rpx 40rpx;
    border-radius: 30rpx;
    border: none;
}

/* 加载状态 */
.loading-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 60rpx 0;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(162, 89, 255, 0.2);
    border-top: 4rpx solid #A259FF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.loading-text {
    font-size: 28rpx;
    color: #B8B8D1;
}

/* 加载更多 */
.load-more {
    text-align: center;
    padding: 30rpx 0;
    font-size: 26rpx;
    color: #B8B8D1;
}

/* 自定义弹窗 */
.custom-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    width: 80%;
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    border-radius: 20rpx;
    border: 1px solid #2D1457;
    box-shadow: 0 10rpx 30rpx rgba(123, 47, 242, 0.3);
    overflow: hidden;
}

.modal-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #A259FF;
    text-align: center;
    padding: 30rpx 0;
    border-bottom: 1px solid rgba(45, 20, 87, 0.5);
}

.modal-body {
    padding: 40rpx 30rpx;
}

.contact-item {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    flex-wrap: wrap;
}

.contact-label {
    font-size: 28rpx;
    color: #B8B8D1;
    margin-right: 10rpx;
}

.contact-value {
    font-size: 28rpx;
    color: #fff;
    flex: 1;
}

.copy-btn {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    color: #fff;
    font-size: 24rpx;
    padding: 6rpx 20rpx;
    border-radius: 30rpx;
    margin-left: 20rpx;
}

.modal-footer {
    padding: 20rpx 30rpx 40rpx;
    display: flex;
    justify-content: center;
}

.modal-btn {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    color: #fff;
    font-size: 28rpx;
    padding: 15rpx 60rpx;
    border-radius: 40rpx;
    border: none;
}
</style>